// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import * as api from './api'
import * as $const from './constants'
import globalBus from './globaBus'
import './filter'
import './elementUIComponents'

Vue.prototype.$api = api
Vue.prototype.$const = $const
Vue.prototype.$globalBus = globalBus

Vue.config.productionTip = false

router.beforeEach((to, from, next) => {
  if (to.meta.noAuth) {
    next()
  } else {
    if (globalBus.USER.id) {
      next()
    } else {
      globalBus.$api.getUser(data => {
        globalBus.USER = data.resource
        next()
      }, e => {
        next({
          path: '/login',
          query: {redirect: to.fullPath}
        })
      })
    }
  }
})

/* eslint-disable no-new */
const vm = new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

// 统一处理ajax数据返回
api.allHandle.handleSuccess = function (data, success, failure) {
  if (data.responseCode === '200') {
    success(data.resultParm)
  } else if (data.responseCode === '401') {
    globalBus.USER = {}
    vm.$router.push('/login')
  } else {
    if (failure) {
      failure(data)
    } else {
      alert(data.message + 'code:' + data.responseCode)
    }
  }
}

// 处理ajax最后的异常
api.allHandle.handleCatch = function (err) {
  console.error(err)
  if (err.toString().indexOf('404')) {
    vm.$notify({
      title: '404',
      message: '没有找到相应接口'
    })
  } else {
    alert('网络请求失败')
  }
}
